package com.le.dub.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.le.dub.common.BusinessRuntimeException;
import com.le.dub.common.ListUtils;
import com.le.dub.conf.UserUtil;
import com.le.dub.conf.RedisKey;
import com.le.dub.mobile.DubRole;
import com.le.dub.mapper.GDubRoleMapper;
import com.le.dub.mobile.bo.AddDubRoleBO;
import com.le.dub.mobile.bo.DubRoleListBO;
import com.le.dub.mobile.vo.DubRoleVO;
import com.le.dub.service.IDubRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.le.dub.service.IVoiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author guole
 * @since 2024-10-09
 */
@Service
public class DubRoleServiceImpl extends ServiceImpl<GDubRoleMapper, DubRole> implements IDubRoleService {
    @Autowired
    private IVoiceService voiceService;
    @Resource
    private RedisTemplate template;
    @Value("${fileServer}")
    private String fileServer;
    @Override
    public Long createDubRole(AddDubRoleBO addDubRoleBO) {
        String key = RedisKey.submitClone + addDubRoleBO.getUserId();
        Long roleId=null;
        if (StrUtil.isEmpty(addDubRoleBO.getRoleName())) {
            throw new BusinessRuntimeException("500", "请输入角色名称");

        }

        //redis锁控制 ，让用户每次只能执行一个任务
        if (!template.opsForValue().setIfAbsent(key, key)) {
            throw new BusinessRuntimeException("500", "当前正在克隆声音，请稍后创建");
        }
        try {

            //创建角色
            DubRole dubRole = new DubRole();
            dubRole.setRoleName(addDubRoleBO.getRoleName());

            dubRole.setRoleType(2);
            dubRole.setCloneStatus(1);
            dubRole.setUserId(addDubRoleBO.getUserId());
            dubRole.setSequence(0);
             dubRole.setUseCount(0);
            dubRole.setSoundUrl(addDubRoleBO.getSoundUrl());
            dubRole.setHead(addDubRoleBO.getHeadUrl());
            dubRole.setCreateTime(new Date());
            this.save(dubRole);
            roleId=dubRole.getId();
            //提交 克隆任务队列
            template.opsForList().rightPush(RedisKey.cloneList, dubRole.getId().toString());
        } catch (BusinessRuntimeException e) {
            //删除用户任务锁
            template.delete(key);
            throw new BusinessRuntimeException(e.getCode(), e.getMsg());

        }
        return roleId;
    }

    @Override
    public void executeClone(Long dubRoleId) {
        String key = null;
        try {
            //获取配音生成记录
            DubRole dubRole = this.getById(dubRoleId);
            String cosyVoiceName = IdUtil.fastUUID().replace("-", "").substring(0, 5) + "v" + dubRoleId;
            dubRole.setCosyVoiceName(cosyVoiceName);
            key = RedisKey.submitClone + dubRole.getUserId();
            String voiceName = voiceService.cloneVoice(dubRole.getCosyVoiceName(), fileServer+dubRole.getSoundUrl());
            //更新配音生成记录
            if (ObjectUtil.isNotNull(voiceName)) {
                dubRole.setCloneStatus(2);
                dubRole.setCosyVoiceName(voiceName);
            } else {
                dubRole.setCloneStatus(3);
            }
            dubRole.setGenerateTime(new Date());
            this.updateById(dubRole);

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //删除用户任务锁
            template.delete(key);


        }
    }

    @Override
    public List<DubRole> cloneRecordListByUser(Long userId) {
        return this.lambdaQuery().eq(DubRole::getCloneStatus,2).eq(DubRole::getUserId,userId).list();
    }

    @Override
    public List<DubRoleVO> dubRoleList(DubRoleListBO dubRoleListBO) {
        return this.baseMapper.dubRoleList(dubRoleListBO);
    }

    @Override
    public List<DubRoleVO> dubCollectList(DubRoleListBO dubRoleListBO) {

        return baseMapper.dubCollectList(dubRoleListBO);
    }

    @Override
    public List<DubRoleVO> dubUserRoleList(DubRoleListBO dubRoleListBO) {


        LambdaQueryWrapper<DubRole> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DubRole::getUserId,dubRoleListBO.getUserId())
                .like(StrUtil.isNotEmpty(dubRoleListBO.getRoleName()),DubRole::getRoleName,dubRoleListBO.getRoleName());
//        if(dubRoleListBO.getSortType()==1){
//            queryWrapper.orderByDesc(DubRole::getUseCount);
//        }
//        if(dubRoleListBO.getSortType()==2){
//            queryWrapper.orderByDesc(DubRole::getCreateTime);
//        }
                    queryWrapper.orderByDesc(DubRole::getCreateTime);

        List<DubRole> dubRoleList=this.list(queryWrapper);
        return ListUtils.copy(dubRoleList,DubRoleVO.class);
    }
}
